package com.example.code06;

import android.content.ContentValues;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.widget.ListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class DetailActivity extends AppCompatActivity {
    private List<News> newsList=new ArrayList<>();
    private HashSet<String> addedTitles = new HashSet<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_news);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        MySQLLiteOpenHelper myDbHelper=new MySQLLiteOpenHelper(DetailActivity.this);
        SQLiteDatabase db=myDbHelper.getReadableDatabase();

        Cursor cursor=db.query(NewsContract.NewsEntry.TABLE_NAME,null,null,null,null,null,null);
        int titleIndex=cursor.getColumnIndex(NewsContract.NewsEntry.COLUMN_NAME_TITLE);
        int authorIndex=cursor.getColumnIndex(NewsContract.NewsEntry.COLUMN_NAME_AUTHOR);
        int imageIndex=cursor.getColumnIndex(NewsContract.NewsEntry.COLUMN_NAME_IMAGE);

        int i=0;
        while(cursor.moveToNext()){
            i++;
            News news=new News();
            String title=cursor.getString(titleIndex);
            String author=cursor.getString(authorIndex);
            String image=cursor.getString(imageIndex);
            news.setmTitle(title);
            news.setmAuthor(author);
            Bitmap bitmap = BitmapFactory.decodeStream(getClass().getResourceAsStream("/" + image));
            news.setmImage(bitmap);
            if (!addedTitles.contains(title)) {
                newsList.add(news);
                addedTitles.add(title); // 将标题添加到HashSet中
            }
        }

        NewsAdapter newsAdapter=new NewsAdapter(DetailActivity.this,R.layout.list_item,newsList);
        ListView listView=findViewById(R.id.lv_news_list);
        listView.setAdapter(newsAdapter);
    }

}